#! /usr/bin/env python3

import base64
import urllib
import requests
import json
import rospy
from std_msgs.msg import String

API_KEY = "iQxqwpkGR8q5kHcuIir9WlRi"
SECRET_KEY = "v3HD1xvlR59WeWrXpYzxNmwHAQWygB2l"
#/home/razgriz/Pictures/ros_nav
rootpath = "/home/agilex/Pictures/ros_nav/"
#language = "ENG"
pub = rospy.Publisher("dingzhen",String,queue_size=10)

def main(index):
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + get_access_token()
    fullpath = rootpath + index + ".jpg"
    # image 可以通过 get_file_content_as_base64("C:\fakepath\test.jpg",True) 方法获取
    payload = "image=" + get_file_content_as_base64(fullpath,True) + "&detect_direction=false&detect_language=false&paragraph=false&probability=false"

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.text)

    resjson = json.loads(response.text)
    length = resjson["words_result_num"]
    try:
        for i in range(0,length):
            res = resjson["words_result"][i]["words"]
            if res in ["A","B","C","D"]:
                if(index == "2"):
                    msg = String()
                    msg.data = res
                    pub.publish(msg)
                    rospy.loginfo("sending message %s",msg.data)
                    break
    except:
        print("解析错误")


def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def doMsg(msg):
    if msg.data == "start":
           for i in ["1","2","3"]:
            main(i)

if __name__ == '__main__':
    rospy.init_node("yiyandingzhen")
    sub = rospy.Subscriber("taking_photo",String,doMsg,queue_size=10)
    rospy.loginfo("zhengzaijianding...")
    rospy.spin()

